#!/usr/bin/env python3
"""
K701数据处理脚本
使用增强版PLOOP处理器处理K701测试数据并生成SVG结果
"""

import sys
import os
import json
import math
from pathlib import Path
from datetime import datetime

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 导入增强版处理器
from enhanced_ploop_processor import EnhancedPLoopProcessor, Vertex

def generate_svg(vertices, title="PLOOP Processing Result", show_grid=True, show_vertices=True, show_fradius=True):
    """生成SVG可视化"""
    if not vertices:
        return "<svg></svg>"
    
    # 计算边界
    min_x = min(v.x for v in vertices)
    max_x = max(v.x for v in vertices)
    min_y = min(v.y for v in vertices)
    max_y = max(v.y for v in vertices)
    
    # 添加边距
    margin = 50
    width = max_x - min_x + 2 * margin
    height = max_y - min_y + 2 * margin
    
    # 坐标转换函数（Y轴翻转）
    def transform(x, y):
        return x - min_x + margin, max_y - y + margin
    
    svg_content = f'''<?xml version="1.0" encoding="UTF-8"?>
<svg width="{width:.0f}" height="{height:.0f}" xmlns="http://www.w3.org/2000/svg">
    <title>{title}</title>
    
    <!-- 背景 -->
    <rect width="100%" height="100%" fill="#f8f9fa"/>
    
    <!-- 网格 -->'''
    
    if show_grid:
        grid_step = 10
        svg_content += f'''
    <defs>
        <pattern id="grid" width="{grid_step}" height="{grid_step}" patternUnits="userSpaceOnUse">
            <path d="M {grid_step} 0 L 0 0 0 {grid_step}" fill="none" stroke="#e0e0e0" stroke-width="0.5"/>
        </pattern>
    </defs>
    <rect width="100%" height="100%" fill="url(#grid)"/>'''
    
    svg_content += '''
    
    <!-- 多边形路径 -->
    <path d="'''
    
    # 生成路径
    for i, vertex in enumerate(vertices):
        tx, ty = transform(vertex.x, vertex.y)
        if i == 0:
            svg_content += f"M {tx:.2f},{ty:.2f}"
        else:
            svg_content += f" L {tx:.2f},{ty:.2f}"
    
    svg_content += ' Z" fill="rgba(76, 175, 80, 0.3)" stroke="#2e7d32" stroke-width="2"/>\n'
    
    # 显示顶点
    if show_vertices:
        svg_content += '''
    <!-- 顶点标记 -->'''
        
        for i, vertex in enumerate(vertices):
            tx, ty = transform(vertex.x, vertex.y)
            
            if vertex.fradius and show_fradius:
                # FRADIUS顶点用红色圆圈标记
                svg_content += f'''
    <circle cx="{tx:.2f}" cy="{ty:.2f}" r="4" fill="#f44336" stroke="white" stroke-width="1"/>
    <text x="{tx + 8:.2f}" y="{ty - 8:.2f}" font-family="Arial" font-size="10" fill="#f44336">
        F{vertex.fradius:.1f}
    </text>'''
            else:
                # 普通顶点用绿色圆圈标记
                svg_content += f'''
    <circle cx="{tx:.2f}" cy="{ty:.2f}" r="3" fill="#2e7d32" stroke="white" stroke-width="1"/>'''
            
            # 顶点编号
            svg_content += f'''
    <text x="{tx + 5:.2f}" y="{ty + 15:.2f}" font-family="Arial" font-size="8" fill="#555">
        {i}
    </text>'''
    
    # 添加标题和统计信息
    svg_content += f'''
    
    <!-- 标题和统计 -->
    <text x="10" y="25" font-family="Arial" font-size="16" font-weight="bold" fill="#333">
        {title}
    </text>
    <text x="10" y="45" font-family="Arial" font-size="12" fill="#666">
        顶点数: {len(vertices)}, FRADIUS: {sum(1 for v in vertices if v.fradius)}
    </text>
    
</svg>'''
    
    return svg_content

def calculate_path_statistics(vertices):
    """计算路径统计信息"""
    if len(vertices) < 2:
        return {}
    
    total_perimeter = 0
    min_edge = float('inf')
    max_edge = 0
    
    for i in range(len(vertices)):
        current = vertices[i]
        next_vertex = vertices[(i + 1) % len(vertices)]
        edge_length = current.distance_to(next_vertex)
        
        total_perimeter += edge_length
        min_edge = min(min_edge, edge_length)
        max_edge = max(max_edge, edge_length)
    
    return {
        "perimeter": total_perimeter,
        "shortest_edge": min_edge,
        "longest_edge": max_edge
    }

def main():
    """主处理函数"""
    
    # 输入和输出路径
    input_file = Path("test-data/1KA-ARCH-P-R-K701.txt")
    output_dir = Path("results_k701")
    
    # 确保输出目录存在
    output_dir.mkdir(exist_ok=True)
    
    print(f"开始处理K701数据...")
    print(f"输入文件: {input_file}")
    print(f"输出目录: {output_dir}")
    
    # 检查输入文件是否存在
    if not input_file.exists():
        print(f"错误：输入文件 {input_file} 不存在")
        return False
    
    try:
        # 创建增强版处理器实例
        processor = EnhancedPLoopProcessor(tolerance=0.1)
        
        # 读取文件内容
        with open(input_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        print(f"✅ 文件读取成功，内容长度: {len(content)} 字符")
        
        # 解析PLOOP数据
        print("\n正在解析PLOOP数据...")
        ploops = processor.parse_file(content)
        print(f"✅ 解析完成，发现 {len(ploops)} 个PLOOP")
        
        # 查找K701 PLOOP
        k701_ploop = None
        for ploop in ploops:
            if 'K701' in ploop.name:
                k701_ploop = ploop
                break
        
        if k701_ploop is None:
            print("❌ 错误: 没有找到K701 PLOOP")
            return False
        
        print(f"\n✅ 找到K701: {k701_ploop}")
        
        # 增强处理
        print("\n正在进行增强处理...")
        processed_vertices = processor.process_ploop_enhanced(k701_ploop)
        
        # 计算统计信息
        stats = calculate_path_statistics(processed_vertices)
        
        # 生成处理报告
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        original_count = len(k701_ploop.vertices)
        processed_count = len(processed_vertices)
        fradius_count = sum(1 for v in processed_vertices if v.fradius)
        optimization_rate = ((original_count - processed_count) / original_count * 100) if original_count > 0 else 0
        
        report = {
            "input_file": str(input_file),
            "processing_timestamp": current_time,
            "original_vertices": original_count,
            "processed_vertices": processed_count,
            "fradius_vertices": fradius_count,
            "optimization_rate": optimization_rate,
            "perimeter": stats.get("perimeter", 0),
            "shortest_edge": stats.get("shortest_edge", 0),
            "longest_edge": stats.get("longest_edge", 0)
        }
        
        # 保存处理报告
        report_file = output_dir / "k701_processing_report.json"
        with open(report_file, 'w', encoding='utf-8') as f:
            json.dump(report, f, indent=2, ensure_ascii=False)
        
        print(f"\n=== K701 处理结果 ===")
        print(f"原始顶点数: {report['original_vertices']}")
        print(f"处理后顶点数: {report['processed_vertices']}")
        print(f"FRADIUS顶点数: {report['fradius_vertices']}")
        print(f"优化率: {report['optimization_rate']:.1f}%")
        print(f"周长: {report['perimeter']:.2f}mm")
        print(f"最短边: {report['shortest_edge']:.3f}mm")
        print(f"最长边: {report['longest_edge']:.2f}mm")
        
        # 生成SVG文件
        svg_file = output_dir / "k701_enhanced.svg"
        svg_content = generate_svg(
            processed_vertices,
            title="K701 Enhanced Processing Result",
            show_grid=True,
            show_vertices=True,
            show_fradius=True
        )
        
        with open(svg_file, 'w', encoding='utf-8') as f:
            f.write(svg_content)
        
        print(f"\nSVG文件已生成: {svg_file}")
        
        # 生成详细分析报告
        analysis_file = output_dir / "k701_analysis.md"
        with open(analysis_file, 'w', encoding='utf-8') as f:
            f.write(f"# K701 处理分析报告\n\n")
            f.write(f"## 基本信息\n")
            f.write(f"- 输入文件: {input_file}\n")
            f.write(f"- 处理时间: {current_time}\n")
            f.write(f"- 处理器版本: Enhanced PLOOP Processor\n\n")
            
            f.write(f"## 处理统计\n")
            f.write(f"- 原始顶点数: {report['original_vertices']}\n")
            f.write(f"- 处理后顶点数: {report['processed_vertices']}\n")
            f.write(f"- FRADIUS顶点数: {report['fradius_vertices']}\n")
            f.write(f"- 优化率: {report['optimization_rate']:.1f}%\n\n")
            
            f.write(f"## 几何分析\n")
            f.write(f"- 总周长: {report['perimeter']:.2f}mm\n")
            f.write(f"- 最短边长: {report['shortest_edge']:.3f}mm\n")
            f.write(f"- 最长边长: {report['longest_edge']:.2f}mm\n\n")
            
            f.write(f"## 处理后顶点详情\n")
            f.write(f"| 编号 | X坐标 | Y坐标 | Z坐标 | FRADIUS |\n")
            f.write(f"|------|-------|-------|-------|----------|\n")
            for i, v in enumerate(processed_vertices):
                frad_str = f"{v.fradius:.2f}mm" if v.fradius else "-"
                f.write(f"| {i} | {v.x:.2f} | {v.y:.2f} | {v.z:.2f} | {frad_str} |\n")
            
            f.write(f"\n## 文件输出\n")
            f.write(f"- SVG可视化: k701_enhanced.svg\n")
            f.write(f"- 处理报告: k701_processing_report.json\n")
            f.write(f"- 分析报告: k701_analysis.md\n")
        
        print(f"分析报告已生成: {analysis_file}")
        print(f"处理报告已保存: {report_file}")
        
        return True
        
    except Exception as e:
        print(f"处理过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = main()
    if success:
        print("\n✅ K701处理完成！")
    else:
        print("\n❌ K701处理失败！")
        sys.exit(1) 